#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Time        : 2021/11/8 13:16
@Author      : Albert Darren
@Contact     : 2563491540@qq.com
@File        : k_means.py
@Version     : Version 1.0.0
@Description : TODO
@Created By  : PyCharm
"""
from joblib import dump
from sklearn.metrics import adjusted_rand_score, adjusted_mutual_info_score, homogeneity_score
from AI.ML.Experiment_8.naive_bayes_classifier import load_data


def train(feature_train):
    """
    训练聚类模型
    :param feature_train: 训练特征集
    :return: 模型
    """
    from sklearn.cluster import KMeans
    k_means = KMeans(n_clusters=3, random_state=0).fit(feature_train)
    dump(k_means, "../models/k_means.model")  # 保存聚类模型对象
    return k_means


def evaluate(model, feature_test, target_test):
    """
    实现有真实标记的聚类模型评估
    :param model: 训练好的模型
    :param feature_test: 测试特征集
    :param target_test: 测试标记集
    :return: 兰德系数得分，互信息得分，同质性得分
    """
    target_pred = model.predict(feature_test)
    rand_score = adjusted_rand_score(target_test, target_pred)  # [-1.0,1.0]
    mutual_score = adjusted_mutual_info_score(target_test, target_pred)  # [0.0,1.0]
    homo_score = homogeneity_score(target_test, target_pred)  # [0.0,1.0]
    return rand_score, mutual_score, homo_score


if __name__ == '__main__':
    # 加载并划分数据集
    DATA_PATH = "../dataset/seeds_dataset.txt"
    attr_train, attr_test, label_train, label_test = load_data(DATA_PATH, delimiter="\t",
                                                               attr_col=7, reindex=(1, 9))
    model_instance = train(attr_train)
    print("兰德系数得分:{}\n互信息得分:{}\n同质性得分:{}".format(*evaluate(model_instance, attr_test, label_test)))
